import { createDiscreteApi } from "naive-ui";
import { errStringInit } from "@/utils";
import $bus from "@/utils/bus";
const $Message = createDiscreteApi(["message"]).message;

const upload = {
  getImg(parameter = { maxSize:20, maxLength: 1, format:[], accept:"*" }, success = ()=>{}) {
    $bus.$off("@/utils/upload.getFile.success");
    $bus.$emit("@/utils/upload.getFile", parameter.accept);
    $bus.$on("@/utils/upload.getFile.success", files => {
      try {
        Object.keys(files).forEach((i) => {
          let extension = files[i].name.split(".").pop().toLowerCase()
          if (files.length > parameter.maxLength) {
            throw new Error(`You can select a maximum of ${parameter.maxLength} file`);
          }
          if (parameter.format && !parameter.format.includes(extension)) {
            throw new Error(`Only ${parameter.format.join(", ")} files are supported`);
          }
          if (files[i].size / 1024 / 1024 > parameter.maxSize) {
            throw new Error(`The size of the uploaded file cannot be larger than ${parameter.maxSize}MB`);
          }
        });
        success(files);
      } catch (error) {
        $Message.warning(`${error.msg || errStringInit(error)}`);
      }
    });
  },
};

export default upload;